import { Button, Form, Input, message } from 'antd'
import { UserOutlined, LockOutlined,VerifiedOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { GlobalTypes } from '@/redux/modules/type';
import { connect } from 'react-redux';
import { ILogin } from '@/api/user/user.type';
import { login } from '@/api/user/user';
import { dealRouteData } from "@/router/dealRoute";
import { remoteList } from '@/api/system/user';
import { removeAll, setCache } from '@/utils/session';
import { useEffect, useState } from 'react';
import Captcha from "react-captcha-code";
import styles from '../index.module.less'
import { rules } from './rules';

const LoginForm = (props: any) => {
    let navigate = useNavigate();
    let [code,setCode] = useState<string>('');
    useEffect(()=>{
        removeAll();
    },[]);
    const onFinish = async (values: ILogin) => {
        let res = await login('master', values);
        let { permissions, token, user } = res.data;
        setCache('token',token)
        let { userId } = user;
        let permissionBox: any[] = []
        if (permissions && permissions.length) {
            permissions.map((item: string) => {
                let getItem = JSON.parse(item);
                permissionBox.push(getItem);
            });
        } else {
            permissionBox = [];
        }
        let userForm = { userId, page: 1, size: 10 };
        let userResult = await remoteList(userForm);
        let userInfo = userResult.data.list[0] || {};
        props.updateToken(token);
        props.updateTenant(user);
        props.updateUserInfo(userInfo);
        dealRouteData(permissionBox);
        navigate('/')
    };
    const onFinishFailed = (errorInfo: any) => {
        console.log('Failed:', errorInfo);
    };
    //验证码切换
    const codeChange =(value: string)=>{
        setCode(value)
    }
    return (
        <>
            <Form
                name="basic"
                style={{ width: '100%' }}
                initialValues={{ remember: true }}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
                autoComplete="off"
            >
                <Form.Item
                    label=""
                    name="username"
                    rules={rules.username}
                >
                    <Input addonBefore={<UserOutlined />} size="large" placeholder='请输入账号' />
                </Form.Item>

                <Form.Item
                    label=""
                    name="password"
                    rules={rules.password}
                >
                    <Input.Password addonBefore={<LockOutlined />} size="large" placeholder='请输入密码' />
                </Form.Item>
                <div className='flex-row'>
                    <div className='flex-item'>
                        <Form.Item
                            label=""
                            name="usercode"
                            rules={[
                                { required: true, message: '请输入验证码！' },
                                {
                                    validator(rule, value, callback) {
                                        if(!value){
                                            callback();
                                        }else if(value!=code){
                                            callback('验证码不正确');
                                        }else{
                                            callback();
                                        }
                                    },
                                }
                            ]}
                        >
                            <Input addonBefore={<VerifiedOutlined />} size="large" placeholder='请输入验证码' />
                        </Form.Item>
                    </div>
                    <div className={styles.code}>
                        <Captcha bgColor={'#283845'} width={120} onChange={codeChange}/>
                    </div>
                </div>
                <Form.Item >
                    <Button type="primary" style={{ width: '100%' }} size='large' htmlType="submit">登 录</Button>
                </Form.Item>
            </Form>
        </>
    )
}

const mapStateToProps = (state: { Global: { token: string; }; }) => {
    return {
        token: state.Global.token
    }
}

const mapDispatchToProps = (dispath: (arg0: { type: string; data: string; }) => any) => {
    return {
        updateToken: (token: string) => dispath({ type: GlobalTypes.UPDATE_TOKEN, data: token }),
        updateTenant: (data: any) => dispath({ type: GlobalTypes.UPDATE_TENANT, data }),
        updateUserInfo: (data: any) => dispath({ type: GlobalTypes.UPDATE_USERINFO, data })
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(LoginForm)
